<template>
  <view class="category-container">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <back-button></back-button>
      <text class="nav-title">商品分类</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar
        v-model="searchKeyword"
        placeholder="搜索商品"
        cancelButton="none"
        @confirm="handleSearch"
        @clear="handleClearSearch"
        bgColor="#f7f7f7"
      ></uni-search-bar>
    </view>

    <!-- 分类内容区 -->
    <view class="category-content">
      <!-- 左侧分类导航 - 使用CategoryList组件 -->
      <category-list
        :categories="categoryList"
        :active-id="currentCategory"
        @select="handleFirstLevelChange"
      ></category-list>

      <!-- 右侧内容区 -->
      <scroll-view 
        class="category-detail" 
        scroll-y
        @scrolltolower="loadMore"
        @refresherrefresh="handleRefresh"
        refresher-enabled
        :refresher-triggered="isRefreshing"
      >
        <!-- 当前分类广告图 -->
        <view class="category-banner" v-if="currentCategoryInfo?.banner">
          <image 
            :src="currentCategoryInfo.banner" 
            mode="aspectFill"
          ></image>
        </view>

        <!-- 二级分类网格 - 使用SubCategoryMenu组件 -->
        <sub-category-menu
          v-if="subCategories.length > 0"
          :title="currentCategoryName"
          :subcategories="subCategories"
          @select="handleSecondLevelChange"
        ></sub-category-menu>

        <!-- 筛选结果提示 -->
        <view class="filter-result" v-if="currentCategoryName">
          <view class="result-header">
            <text class="result-count" v-if="totalCount">{{ totalCount }}件商品</text>
          </view>
        </view>

        <!-- 商品列表区域 - 使用ProductGridItem组件 -->
        <view class="product-section">
          <view class="product-grid">
            <product-grid-item
              v-for="item in productList"
              :key="item.id"
              :product="item"
            ></product-grid-item>
          </view>
          <view class="empty-state" v-if="productList.length === 0 && !isLoading">
            <image src="/static/images/empty.png" mode="aspectFit" class="empty-icon"></image>
            <text class="empty-text">暂无商品</text>
          </view>
        </view>

        <!-- 加载更多 -->
        <uni-load-more :status="loadMoreStatus" @loadmore="loadMore"></uni-load-more>
      </scroll-view>
    </view>
  </view>
</template>


<script>
import CategoryList from '@/components/category/CategoryList'
import SubCategoryMenu from '@/components/category/SubCategoryMenu'
import ProductGridItem from '@/components/product/ProductGridItem'
import BackButton from '@/components/common/BackButton'

export default {
  components: {
    CategoryList,
    SubCategoryMenu,
    ProductGridItem,
    BackButton
  },
  data() {
    return {
      searchKeyword: '',
      categoryList: [], // 一级分类列表
      currentCategory: '', // 当前选中的一级分类ID
      currentCategoryName: '', // 当前选中的一级分类名称
      currentCategoryInfo: null,
      subCategories: [], // 二级分类列表
      selectedSecondLevel: '', // 选中的二级分类ID
      selectedSecondLevelName: '', // 选中的二级分类名称
      productList: [],
      totalCount: 0,
      page: 1,
      pageSize: 10,
      hasMore: true,
      loadMoreStatus: 'more', // more, loading, noMore
      isLoading: false, // 页面加载状态
      isRefreshing: false, // 下拉刷新状态
      categoryCache: {}, // 分类缓存
      productCache: {} // 商品缓存
    }
  },
  computed: {
    // 筛选结果提示文本
    filterResultText() {
      if (this.selectedSecondLevelName) {
        return this.selectedSecondLevelName
      }
      return this.currentCategoryName
    },
    
    // 当前的缓存键
    currentCacheKey() {
      const categoryId = this.selectedSecondLevel || this.currentCategory
      return `${categoryId}_${this.searchKeyword}`
    }
  },
  onLoad(options) {
    // 如果有URL参数，保存起来以便加载完分类后使用
    this.options = options
    this.loadCategories()
  },
  onPullDownRefresh() {
    this.handleRefresh()
  },
  onShareAppMessage() {
    // 分享当前分类页面
    const categoryName = this.selectedSecondLevelName || this.currentCategoryName || '商品分类'
    return {
      title: `${categoryName} - 商品分类`,
      path: `/pages/product/category/index?categoryId=${this.currentCategory}&subCategoryId=${this.selectedSecondLevel}`
    }
  },
  methods: {
    // 处理页面刷新
    async handleRefresh() {
      this.isRefreshing = true
      this.resetProductList()
      await this.loadProducts()
      this.isRefreshing = false
      uni.stopPullDownRefresh()
    },
    
    // 加载一级分类
    async loadCategories() {
      if (this.isLoading) return
      
      this.isLoading = true
      uni.showLoading({ title: '加载中...' })
      
      try {
        // 使用新的API调用获取分类树
        const res = await this.$api.product.category.getTree()
        
        if (res.code === 200) {
          // 筛选出一级分类
          this.categoryList = res.data.filter(item => item.level === 1 || item.parentId === 0)
          
          // 处理URL参数
          if (this.options?.categoryId && this.categoryList.length > 0) {
            // 如果URL中有分类ID参数，选择对应分类
            const targetCategory = this.categoryList.find(item => item.id == this.options.categoryId)
            if (targetCategory) {
              this.handleFirstLevelChange(targetCategory, this.options.subCategoryId)
              uni.hideLoading()
              this.isLoading = false
              return
            }
          }
          
          // 默认选择第一个分类
          if (this.categoryList.length > 0) {
            this.handleFirstLevelChange(this.categoryList[0])
          }
        } else {
          this.handleApiError(res, '加载分类失败')
        }
      } catch (error) {
        console.error('加载分类失败:', error)
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.isLoading = false
      }
    },

    // 处理一级分类切换
    async handleFirstLevelChange(category, subCategoryId = '') {
      if (this.isLoading || this.currentCategory === category.id) return
      
      this.currentCategory = category.id
      this.currentCategoryName = category.name
      this.selectedSecondLevel = ''
      this.selectedSecondLevelName = ''
      
      // 显示加载指示器
      this.isLoading = true
      
      try {
        // 检查缓存中是否有该分类的详情
        const cacheKey = `category_${category.id}`
        if (this.categoryCache[cacheKey]) {
          this.currentCategoryInfo = this.categoryCache[cacheKey].info
          this.subCategories = this.categoryCache[cacheKey].subs
          
          // 如果有子分类ID参数，选择对应子分类
          if (subCategoryId && this.subCategories.length > 0) {
            const targetSubCategory = this.subCategories.find(item => item.id == subCategoryId)
            if (targetSubCategory) {
              this.selectedSecondLevel = targetSubCategory.id
              this.selectedSecondLevelName = targetSubCategory.name
            }
          } else if (this.subCategories.length > 0) {
            // 如果没有指定子分类ID，自动选择第一个子分类
            const firstSubCategory = this.subCategories[0]
            this.selectedSecondLevel = firstSubCategory.id
            this.selectedSecondLevelName = firstSubCategory.name
          }
          
          // 加载商品列表
          this.resetProductList()
          await this.loadProducts()
          this.isLoading = false
          return
        }
        
        // 并行获取分类详情和子分类
        const [detailRes, childrenRes] = await Promise.all([
          this.$api.product.category.getById(category.id),
          this.$api.product.category.getChildren(category.id)
        ])
        
        if (detailRes.code === 200) {
          this.currentCategoryInfo = detailRes.data
        } else {
          this.handleApiError(detailRes, '加载分类详情失败')
        }

        if (childrenRes.code === 200) {
          this.subCategories = childrenRes.data
          
          // 如果有子分类ID参数，选择对应子分类
          if (subCategoryId && this.subCategories.length > 0) {
            const targetSubCategory = this.subCategories.find(item => item.id == subCategoryId)
            if (targetSubCategory) {
              this.selectedSecondLevel = targetSubCategory.id
              this.selectedSecondLevelName = targetSubCategory.name
            }
          } else if (this.subCategories.length > 0) {
            // 如果没有指定子分类ID，自动选择第一个子分类
            const firstSubCategory = this.subCategories[0]
            this.selectedSecondLevel = firstSubCategory.id
            this.selectedSecondLevelName = firstSubCategory.name
          }
          
          // 缓存分类详情和子分类
          this.categoryCache[cacheKey] = {
            info: this.currentCategoryInfo,
            subs: this.subCategories
          }
        } else {
          this.handleApiError(childrenRes, '加载子分类失败')
        }
        
        // 重置商品列表并加载商品
        this.resetProductList()
        await this.loadProducts()
      } catch (error) {
        console.error('加载分类详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },

    // 处理二级分类切换
    async handleSecondLevelChange(category) {
      if (this.selectedSecondLevel === category.id) {
        // 如果点击当前选中的二级分类，则取消选择
        this.selectedSecondLevel = ''
        this.selectedSecondLevelName = ''
      } else {
        this.selectedSecondLevel = category.id
        this.selectedSecondLevelName = category.name
      }
      
      // 重置并重新加载商品列表
      this.resetProductList()
      await this.loadProducts()
    },
    
    // 重置商品列表
    resetProductList() {
      this.productList = []
      this.page = 1
      this.hasMore = true
      this.loadMoreStatus = 'more'
    },

    // 加载商品列表
    async loadProducts() {
      if (!this.hasMore || this.loadMoreStatus === 'loading') return
      
      this.loadMoreStatus = 'loading'
      
      try {
        // 准备请求参数
        const requestParams = {
          pageNum: this.page,
          pageSize: this.pageSize
        }

        if (this.searchKeyword) {
          requestParams.keyword = this.searchKeyword
        }

        // 获取分类ID参数
        const categoryIds = []
        if (this.currentCategory) {
          categoryIds.push(this.currentCategory)
        }
        if (this.selectedSecondLevel) {
          categoryIds.push(this.selectedSecondLevel)
        }
        
        if (categoryIds.length === 0) {
          this.loadMoreStatus = 'noMore'
          return
        }
        
        // 将分类ID添加到参数中
        requestParams.categoryIds = categoryIds.join(',')
        
        // 检查缓存中是否有数据
        if (this.page === 1 && this.productCache[this.currentCacheKey]) {
          const cachedData = this.productCache[this.currentCacheKey]
          const cacheTime = cachedData.timestamp || 0
          const now = Date.now()
          // 缓存时间小于5分钟则使用缓存
          if (now - cacheTime < 5 * 60 * 1000) {
            this.productList = cachedData.list
            this.totalCount = cachedData.total
            this.hasMore = cachedData.hasMore
            this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
            this.page++
            return
          }
        }

        // 增加调试日志
        console.log('请求参数:', requestParams)

        // 根据选择的分类使用不同的API端点
        let res = null
        
        if (this.selectedSecondLevel) {
          // 如果选择了二级分类，使用getProducts API
          res = await this.$api.product.category.getProducts(this.selectedSecondLevel, requestParams)
        } else if (this.currentCategory) {
          // 如果只选择了一级分类，使用getProducts API
          res = await this.$api.product.category.getProducts(this.currentCategory, requestParams)
        } else if (categoryIds.length > 0) {
          // 使用多级分类筛选商品
          res = await this.$api.product.category.getFilteredProducts(categoryIds, requestParams)
        }
        
        console.log('商品查询响应:', res)
        
        if (res && res.code === 200) {
          // 获取返回的商品列表，支持不同的返回格式
          let list = [];
          
          // 处理不同的返回数据结构
          if (res.data.records) {
            // 如果数据在records字段中
            list = res.data.records || [];
            this.totalCount = res.data.total || 0;
          } else if (res.data.list) {
            // 如果数据在list字段中
            list = res.data.list || [];
            this.totalCount = res.data.total || 0;
          } else if (Array.isArray(res.data)) {
            // 如果数据直接是数组
            list = res.data;
            this.totalCount = list.length;
          } else {
            console.error('未知的数据格式:', res.data);
            list = [];
          }
          
          // 统一处理商品数据格式
          list = list.map(item => {
            // 确保图片路径的一致性
            if (!item.mainImage && item.image) {
              item.mainImage = item.image;
            }
            
            // 如果既没有mainImage也没有image，设置默认图片
            if (!item.mainImage && !item.image) {
              item.mainImage = '/static/images/default-product.png';
            }
            
            // 确保价格数据正确
            if (typeof item.price === 'undefined') {
              item.price = 0;
            }
            
            // 确保销量数据正确
            if (typeof item.sales === 'undefined') {
              item.sales = 0;
            }
            
            // 确保tags是数组
            if (!item.tags) {
              item.tags = [];
            }
            
            return item;
          });
          
          console.log('处理后的商品列表:', list);
          
          if (this.page === 1) {
            this.productList = list;
            
            // 更新商品缓存
            this.productCache[this.currentCacheKey] = {
              list: [...list],
              total: this.totalCount,
              hasMore: list.length === this.pageSize,
              timestamp: Date.now()
            };
          } else {
            this.productList = [...this.productList, ...list];
          }
          
          this.hasMore = list.length === this.pageSize;
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore';
          this.page++;
        } else {
          this.handleApiError(res, '加载失败');
          this.loadMoreStatus = 'more';
        }
      } catch (error) {
        console.error('加载商品失败:', error)
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: '加载商品失败',
          icon: 'none'
        })
      }
    },

    loadMore() {
      this.loadProducts()
    },

    handleSearch() {
      this.resetProductList()
      this.loadProducts()
    },

    handleClearSearch() {
      this.searchKeyword = ''
      this.resetProductList()
      this.loadProducts()
    },
    
    handleImageError(index) {
      console.error(`商品图片加载失败，索引: ${index}`)
      // 可以在这里设置默认图片
      if (this.productList[index]) {
        this.productList[index].imageError = true
      }
    },
    
    // 统一处理API错误
    handleApiError(res, defaultMessage) {
      console.error('API错误:', res)
      uni.showToast({
        title: res.message || defaultMessage,
        icon: 'none'
      })
    },
    
    // 清除缓存
    clearCache() {
      this.categoryCache = {}
      this.productCache = {}
    }
  }
}
</script>

<style lang="scss" scoped>
.category-container {
  min-height: 100vh;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 100;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .nav-title {
    flex: 1;
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    text-align: center;
  }
  
  .nav-right {
    width: 88rpx;
  }
}

.search-bar {
  position: fixed;
  top: 88rpx;
  left: 0;
  right: 0;
  z-index: 99;
  background: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  :deep(.uni-searchbar) {
    padding: 0;
    background: transparent;
    
    .uni-searchbar__box {
      height: 72rpx;
      border-radius: 36rpx;
      background: #f7f7f7;
      border: none;
      
      .uni-searchbar__text-input {
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.category-content {
  display: flex;
  margin-top: 200rpx;
  height: calc(100vh - 200rpx);
  
  :deep(.category-list) {
    width: 180rpx;
    height: 100%;
    background: #fff;
    overflow-y: auto;
    
    .category-item {
      height: 100rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #666;
      position: relative;
      
      &.active {
        color: $uni-primary;
        font-weight: 500;
        background: #fff;
        
        &::after {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 6rpx;
          height: 36rpx;
          background: $uni-primary;
          border-radius: 0 3rpx 3rpx 0;
        }
      }
    }
  }
  
  .category-detail {
    flex: 1;
    height: 100%;
    background: #fff;
    padding: 20rpx;
    
    .category-banner {
      width: 100%;
      height: 240rpx;
      border-radius: 16rpx;
      overflow: hidden;
      margin-bottom: 30rpx;
      
      image {
        width: 100%;
        height: 100%;
      }
    }
    
    :deep(.sub-category-menu) {
      margin-bottom: 30rpx;
      
      .menu-title {
        font-size: 32rpx;
        color: #333;
        font-weight: 500;
        margin-bottom: 20rpx;
      }
      
      .menu-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 20rpx;
        
        .menu-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 20rpx;
          background: #f8f8f8;
          border-radius: 12rpx;
          transition: all 0.3s;
          
          &:active {
            transform: scale(0.98);
          }
          
          .item-icon {
            width: 80rpx;
            height: 80rpx;
            margin-bottom: 12rpx;
          }
          
          .item-name {
            font-size: 24rpx;
            color: #666;
          }
          
          &.active {
            background: rgba($uni-primary, 0.1);
            
            .item-name {
              color: $uni-primary;
              font-weight: 500;
            }
          }
        }
      }
    }
    
    .filter-result {
      margin-bottom: 20rpx;
      
      .result-header {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;
        
        .result-count {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
    
    .product-section {
      .product-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20rpx;
        
        :deep(.product-grid-item) {
          background: #fff;
          border-radius: 16rpx;
          overflow: hidden;
          box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
          
          .product-image {
            width: 100%;
            aspect-ratio: 1;
            border-radius: 16rpx 16rpx 0 0;
          }
          
          .product-info {
            padding: 20rpx;
            
            .product-name {
              font-size: 28rpx;
              color: #333;
              line-height: 1.4;
              margin-bottom: 12rpx;
              @include text-ellipsis(2);
            }
            
            .product-price {
              color: $uni-primary;
              font-size: 32rpx;
              font-weight: bold;
              
              &::before {
                content: '¥';
                font-size: 24rpx;
                margin-right: 4rpx;
              }
            }
            
            .product-stats {
              display: flex;
              align-items: center;
              margin-top: 12rpx;
              font-size: 22rpx;
              color: #999;
              
              .stat-item {
                margin-right: 16rpx;
              }
            }
          }
        }
      }
    }
    
    .empty-state {
      padding: 60rpx 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .empty-icon {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
      }
      
      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

:deep(.uni-load-more) {
  padding: 30rpx 0;
}
</style> 